package com.zzx.boot.gilter;

import com.google.gson.Gson;
import com.zzx.boot.constant.GlobalEnum;
import com.zzx.boot.constant.PreFix;
import com.zzx.boot.constant.Time;
import com.zzx.boot.entity.table.LoginUser;
import com.zzx.boot.exception.SystemctlException;
import com.zzx.boot.utils.JWTUtil;
import com.zzx.boot.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author tan
 * @version 1.0
 * @date 2023/7/8 22:53
 */
@Component
public class JwtFilter extends OncePerRequestFilter {

    @Resource
    private JWTUtil jwtUtil;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private Gson gson;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 判断用户是否携带token
        String authorization = request.getHeader("authorization");

        if(!StringUtils.hasLength(authorization)){
            filterChain.doFilter(request,response);
            return;
        }
        // 认证授权
        // 判断token是否过期
        // 判断token是否合法
        String userId = "";
        LoginUser loginUser = null;

        try{
           Claims claims = jwtUtil.parseToken(authorization);
           if(claims!=null){
               userId = claims.getSubject();
           }
       }catch (ExpiredJwtException e){
            request.setAttribute("err",new SystemctlException(GlobalEnum.TOKEN_EXPIRED));
            request.getRequestDispatcher("/zzx/error").forward(request,response);
            return;
       }


     try{
         // 从redis中获取
          loginUser =  redisUtils.getString(PreFix.LOGIN_PREFIX+userId,LoginUser.class);
          if(loginUser==null){
              request.setAttribute("err",new SystemctlException(GlobalEnum.REDIS_PARSE_ERROR));
              request.getRequestDispatcher("/zzx/error").forward(request,response);
              return;
          }
         redisUtils.setStringEx(PreFix.LOGIN_PREFIX+loginUser.getUser().getId(),gson.toJson(loginUser), Time.TOKEN_TIME.longValue(), TimeUnit.SECONDS);
     }catch (Exception e){
         e.printStackTrace();
     }
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(loginUser, true, null);
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request,response);
        return;

    }
}
